<?php

namespace Home\Controller;

use Think\Controller;

class ApiController extends Controller
{
    //检测邮箱是否存在
    public function checkemail()
    {
        $email = I('get.email');
        $user = M('User');
        $result = $user->where("username='%s'", $email)->find();
        if ($result) {
            $data['status'] = 1;
        } else {
            $data['status'] = 0;
        }
        $this->ajaxReturn($data);
    }

    //购买付款的页面
    public function payvip(){

        // 得到会员要购买的时限
        $num = $_GET['buynum'];
        //得到要购买会员的用户的ID
        $vip['user_id'] = $_GET['id'];
        //得到验证的vip_key
        $vip['vip_key'] = $_GET['vipkey'];
        //实例化vip
        $vipdb = M('vip');
        $res = $vipdb -> field('vip_id,vip_value') ->  where($vip) ->select();

        // var_dump($res);
        // var_dump($_SESSION['vipvalue']);
        if ($res[0]['vip_value'] == $_GET['vipvalue']) {
            //修改数据库中的状态
            $data['status'] = 1;
            $vipdb -> where('vip_id='.$res[0]['vip_id']) -> save($data);
            // echo $vipdb -> _sql();die;
            //得到用户的信息
            $user_info = M('user_info');
            $result = $user_info -> field('zz_user_info.nickname,zz_user_info.photo,zz_user_info.vipday,zz_user_info.exp,zz_user.username')
                                                -> join('zz_user ON zz_user.user_id = zz_user_info.user_id')
                                                ->where('zz_user_info.user_id='.$_GET['id'])
                                                ->select();
            $this -> assign('nickname',$result[0]['nickname']);
            $this -> assign('username',$result[0]['username']);
            $this -> assign('photo',$result[0]['photo']);
            $this -> assign('exp',$result[0]['exp']);
            $this -> assign('grade', floor(sqrt( $result[0]['exp'] ) ) );
            //当未开通vip 或vip已过期
            if ( $result[0]['vipday'] < time() ) {
                //将开通会员的时限存入数组
                //得到实现的秒化
                $test['vipday'] = time() + $num * 30 * 24 * 3600;
                $user_info -> where('user_id='.$_GET['id']) -> save($test);
                $vipday = $num * 30;
            }else{   //当该用户之前购买的会员还没有过期的情况下
                $test['vipday'] = $result[0]['vipday'] + $num * 30 * 24 * 3600;
                $user_info -> where('user_id='.$_GET['id']) -> save($test);
                $vipday  = ( $test['vipday'] -time() ) / 24 /3600;
            }
            $this -> assign('vipday',ceil( $vipday ).'天' );
            $this -> assign('test','支付处理');
            $this -> display();
        }else{
            echo '抱歉~连接已失效~';
        }
    }

}
